﻿namespace CN2P.Web.Controllers.Api
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using CN2P.ServiceModel;

    public class SessionApiController : BaseApiController
    {
        private static readonly List<SessionItemModel> Items = new List<SessionItemModel>();
        private static readonly object Sync = new object();

        [AcceptVerbs("GET")]
        public IList<SessionItemModel> Get(string userId, int count = int.MaxValue)
        {
            var decodedUserId = this.DecodeUserId(userId);
            lock (Sync)
            {
                var items = Items
                    .Where(item => item.UserId == decodedUserId)
                    .Take(count)
                    .ToList();
                return items;
            }
        }

        [AcceptVerbs("POST")]
        public HttpResponseMessage Post([FromBody]SessionItemModel item)
        {
            lock (Sync)
            {
                Items
                    .Where(si => si.UserId == item.UserId && si.ProdId == item.ProdId)
                    .ToList()
                    .ForEach(si => Items.Remove(si));
                Items.Insert(0, item);
            }

            return Request.CreateResponse(HttpStatusCode.Created);
        }
    }
}
